package com.tony.juc;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: RecursiveTaskDemo001
 * @Auther: 皮蛋布丁
 * @Date: 2022/04/19/21:51
 * @Description: RecursiveTask分支任务(有返回值).
 */
public class RecursiveTaskDemo001 {

    public static void main(String[] args) throws Exception{
        RecursiveTaskSumTask task = new RecursiveTaskSumTask(1,100); //外部的计算操作
        ForkJoinPool pool = new ForkJoinPool(); //开启分支任务池
        Future<Integer> future = pool.submit(task); //执行分支任务
        System.out.println("分支任务计算结算：" + future.get()); //异步返回
    }
}
class RecursiveTaskSumTask extends RecursiveTask<Integer> {
    private static final int THRESHOLD = 25; //分支阈值
    private int start; //开始计算数值
    private int end; //结束计算数值

    public RecursiveTaskSumTask(int start, int end) { //数据的累加配置
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() { //完成计算的处理
        //所有的子分支的处理，以及所有相关分支的合并处理都在此方法之中完成
        int sum = 0; //保存最终的计算结果
        boolean isFork = (end - start) <= THRESHOLD; //是否需要进行分支
        if (isFork) {
            for (int i = start ; i <= end ; i++) {
                sum += i; //分支处理
            }
            System.out.printf("【%s】start = %d、end = %d、sum = %d%n",Thread.currentThread().getName(),this.start,
                    this.end,sum);
        } else { //需要开启分支
            int middle = (start + end) / 2;
            RecursiveTaskSumTask leftTask = new RecursiveTaskSumTask(this.start,middle);
            RecursiveTaskSumTask rightTask = new RecursiveTaskSumTask(middle + 1,this.end);
            leftTask.fork(); //开启做分支
            rightTask.fork(); //开启右分支
            sum = leftTask.join() + rightTask.join(); //等待分支处理的执行结果返回
        }

        return sum;
    }
}
